import React from 'react';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {hasPermissions} from './utils';
import {testDriveStatus} from '../Enum';
import {
    TABLE,
    DATETIME_FORMAT,
    PAGINATION_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    FIXED_COLUMN_WIDTH
} from '../constants';
import {conventEnumValueToString, formatDateTime} from '../utils';
import {PERMISSION} from './constants';
import {abandonOrder, effectiveOrder} from './api';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {injectIntl} from './intl';
export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
        };
    }

    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };

    onClickAbandonBtn = id => {
        this.setState({loading: true});
        const record = this.props.data.find(d => d.id === id);
        abandonOrder(id, record.rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onClickEffectiveBtn = id => {
        this.setState({loading: true});
        const record = this.props.data.find(d => d.id === id);
        effectiveOrder(id, record.rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }

    render() {
        const {formatMessage} = this.props.intl;
        const {pageIndex, pageSize, total, permissions} = this.props;
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const columns = [{
            title: formatMessage({
                id: 'tablePanel.column.code',
                defaultMessage: '试乘试驾编号',
            }),
            dataIndex: 'code',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
            render: (text, record) => <Link to={routes.detail.format(record.id)} >{text}</Link>
        }, {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.brand',
                defaultMessage: '品牌'
            }),
            dataIndex: 'brand',
            render: (text, record) => `(${record.brandCode})${record.brandName}`
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.dealerCode',
                defaultMessage: '总代编号'
            }),
            dataIndex: 'dealerCode',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'dealerCode' && this.props.sortedOrder,
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.dealerName',
                defaultMessage: '总代名称'
            }),
            dataIndex: 'dealerName',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'dealerName' && this.props.sortedOrder,
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.subDealerCode',
                defaultMessage: '二级服务站编号'
            }),
            dataIndex: 'subDealerCode',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'subDealerCode' && this.props.sortedOrder,
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.subDealerName',
                defaultMessage: '二级服务站名称'
            }),
            dataIndex: 'subDealerName',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'subDealerName' && this.props.sortedOrder,
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.customerCode',
                defaultMessage: '客户编号'
            }),
            dataIndex: 'customerCode',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'customerCode' && this.props.sortedOrder,
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.customerName',
                defaultMessage: '客户姓名'
            }),
            dataIndex: 'customerName',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'customerName' && this.props.sortedOrder,
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.userName',
                defaultMessage: '使用人姓名'
            }),
            dataIndex: 'userName',
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.VIN',
                defaultMessage: 'VIN'
            }),
            dataIndex: 'vIN',
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.testDriveYear',
                defaultMessage: '试乘试驾年份'
            }),
            dataIndex: 'testDriveYear',
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.testDriveMonth',
                defaultMessage: '试乘试驾月份'
            }),
            dataIndex: 'testDriveMonth',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.createTime',
                defaultMessage: '创建时间'
            }),
            dataIndex: 'createTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.status',
                defaultMessage: '状态',
            }),
            dataIndex: 'status',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'status' && this.props.sortedOrder,
            render: text => conventEnumValueToString(testDriveStatus, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.operate',
                defaultMessage: '操作'
            }),
            dataIndex: 'operate',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [{
                    id: PERMISSION.update,
                    children: <Link key="update" to={routes.update.format(r.id)}>{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.update',
                            defaultMessage: '编辑'
                        })
                    }</Link>,
                    hidden: !(hasPermissions(permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update)),
                },
                {
                    id: PERMISSION.abandon,
                    children: (ref =>
                        <WrappedPopconfirm
                            key="abandon"
                            placement="topLeft"
                            onConfirm={this.onClickAbandonBtn}
                            onVisibleChange={ref.setMenuVisible}
                            id={r.id}
                            title={this.props.intl.formatMessage({
                                id: 'tablePanel.validate.abandon',
                                defaultMessage: '是否确认作废？'
                            })}>
                            <a>{
                                this.props.intl.formatMessage({
                                    id: 'tablePanel.abandon',
                                    defaultMessage: '作废'
                                })
                            }</a>
                        </WrappedPopconfirm>
                    ),
                    hidden: !(hasPermissions(permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon)),
                },
                {
                    id: PERMISSION.effective,
                    children: (ref =>
                        <WrappedPopconfirm
                            key="effective"
                            placement="topLeft"
                            onConfirm={this.onClickEffectiveBtn}
                            onVisibleChange={ref.setMenuVisible}
                            id={r.id}
                            title={this.props.intl.formatMessage({
                                id: 'tablePanel.validate.effective',
                                defaultMessage: '是否确认生效？'
                            })}>
                            <a>{
                                this.props.intl.formatMessage({
                                    id: 'tablePanel.effective',
                                    defaultMessage: '生效'
                                })
                            }</a>
                        </WrappedPopconfirm>
                    ),
                    hidden: !(hasPermissions(permissions, PERMISSION.effective) && hasPermissions(r.options, PERMISSION.effective)),
                }];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        }];
        return (
            <div>
                <Table className="white-space-nowrap"
                    dataSource={this.props.data}
                    rowKey="id"
                    columns={columns}
                    pagination={pagination}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    {...TABLE} >
                </Table>
            </div>
        );
    }
}

TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    errorMessage: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    refreshListData: PropTypes.func,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {
    tableSearch,
} from './actions';
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state),
});
const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch()),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));

